package com.lml.redis;

import org.junit.jupiter.api.Test;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @date 2021/6/3 15:49
 * Description:
 */
public class TestRedisson {
    Jedis jedis = new Jedis("localhost", 6379);

    public RedissonClient configRedisson() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://localhost:6379");
        config.setCodec(new StringCodec());
        //设置看门狗的时间，不配置的话默认30000
        config.setLockWatchdogTimeout(12000);
        return Redisson.create(config);
    }

    /**
     * 原文链接：https://blog.csdn.net/qq_41762594/article/details/108963412
     *
     * @return
     * @throws InterruptedException
     */
    public void getWatchDog() throws InterruptedException {
        RLock watchDog = configRedisson().getLock("watchDog");
        boolean judge;
        //进行3s的尝试时间，如果失败则返回false， 还可以设置锁过期时间，如果设置会导致看门狗无效
        judge = watchDog.tryLock(3, TimeUnit.SECONDS);
        //输出是否能够获取到锁
        System.out.println(Thread.currentThread().getName() + "的锁获取情况：" + judge);
        //如果获取到锁
        if (judge) {
            try {
                System.out.println(Thread.currentThread().getName() + " 已经成功获取到的分布式锁" + System.currentTimeMillis());
                //执行主要业务逻辑
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                //最后进行解锁操作，如果服务宕机，则到不了这一步，会等待看门狗监控锁结束锁清除
                System.out.println(Thread.currentThread().getName() + " 进行解锁操作" + System.currentTimeMillis());
                watchDog.unlock();
            }
        } else {
            //如果没有获取到分布式锁，执行业务逻辑
            System.out.println(Thread.currentThread().getName() + " 没有成功获取到分布式锁，锁已经被占用" + System.currentTimeMillis());
        }
        //最后输出
        if (judge) {
            System.out.println("成功获取到分布式锁");
        }
        System.out.println("没有获取到分布式锁");
    }

    @Test
    public void lock() {
        SetParams setParams = new SetParams();
        setParams.ex(20);
        setParams.nx();
        System.out.println(jedis.set("lockKey", "value", setParams));
        System.out.println(jedis.set("lockKey", "value", setParams));
    }

    @Test
    public void test01() {
        SetParams setParams = new SetParams();
        setParams.ex(20);
        setParams.nx();
        //原子性操作 setnx ex
        jedis.set("watchDog", "value", setParams);

        System.out.println(jedis.ping());
//        SetParams setParams = new SetParams();
//        setParams.ex(20);
//        setParams.nx();
//        //原子性操作 setnx ex
//        jedis.set("watchDog", "value", setParams);
//        new TestRedisson().getWatchDog();
    }
}
